package impl;

import interfaces.ChatProxy;
import interfaces.ChatServer;
import interfaces.ClientProxy;
import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.text.SimpleDateFormat;
import servlet.ClientServlet;

/**
 * Methodimplementation of clientproxy.
 * Implements methods for server to communicate with clients.
 *
 * @author Dominik Korittki
 * @author Steffen Grushka
 * @version 0.1
 */
public class ClientProxyImpl extends UnicastRemoteObject implements ClientProxy {

	private static final long serialVersionUID = 1L;
	private ChatProxy chat;
	private ChatServer chatServer;
        private ClientServlet clientServlet;
	private String username;
	private String ip;
	
	public ClientProxyImpl(String username, String ip, 
                ClientServlet clientServlet) 
                throws RemoteException, AccessException, NotBoundException {
            super();
            this.username = username;
            this.ip = ip;
            this.clientServlet = clientServlet;
            Registry registry = LocateRegistry.getRegistry(ip);
            chatServer = (ChatServer) registry.lookup("ChatServer");

            chat = chatServer.subscribeUser(username, this);
	}
	
	@Override
	public void receiveMessage(String username, String message) throws RemoteException {
            clientServlet.storeMessage(username, message, this.username);
            
            /*
            SimpleDateFormat sdf = new SimpleDateFormat();
	    sdf.applyPattern( "hh:mm:ss" );
	    
		//gui.appendMessage(username + "(" + sdf.format(new Date()) + "): " + message);
                * 
            */
	}
	
	/**
	 * called by gui actionlistener to send a message to the chatserver
	 * @param message
	 */
	public void sendMessage(String message) {
		try {
			chat.sendMessage(message);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * called by gui listener if clients close the window.
	 * disconnects from server
	 */
	public void logout() {
		try {
			if(chatServer != null)
				chatServer.unsubscribeUser(username);
		} catch (RemoteException e) {}
	}

        
	/**
	 * creates new clientproxyimpl(this class) object
	 * @param args
	 */
        /*
	public static void main(String[] args) {
		try {
			new ClientProxyImpl();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
        * 
        */

}
